<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends CommonController {
    public function test(){
        // $wid = 29;
        // $map['wid'] = $wid;
        // M("Cate")->where($map)->delete();

        // $cate_map['wid'] = 2;
        // $cate_map['pid'] = 0;
        // $sub_map['wid'] = 2;
        // $cates = M("Cate")->where($cate_map)->select();
        // foreach ($cates as $key => $value) {
        //     $sub_map['pid'] = $value['id'];
        //     unset($value['id']);
        //     $value['wid'] = $wid;
        //     // dump($value);
        //     echo "<br/><br/>";
        //     echo $pid = M("Cate")->add($value);
        //     // dump($sub_map);
        //     $sub_cates = M("Cate")->where($sub_map)->select();
        //     foreach ($sub_cates as $k => $v) {
        //         unset($v['id']);
        //         $v['wid'] = $wid;
        //         $v['pid'] = $pid;
        //         // dump($v);
        //         echo M("Cate")->add($v);
        //         echo "<br/>";
        //     }
        // }
        $map['wid'] = 2;

        $list = M("Info")->where($map)->group('cate')->select();
        foreach ($list as $key => $value) {
            $map['title'] = $value['cate'];
            if(M("Cate")->where($map)->find()){
                $new['id'] = $value['cid']; 
                M("Cate")->where($map)->save($new);
                // M("Cate")->where($map)->save($new);
            }
        }
    }
    public function index(){
    	$appid = C("OPEN_APPID");
        if($_GET['auth_code']){
            $this->redirect('get_auth_info',$_GET);
            // $this->get_auth_info();
        }
        $map['uid'] = session('uid');
        $list = M("Wechat")->where($map)->select();
        $this->assign('list',$list);

    	$appid = C("OPEN_APPID");
    	$pre_auth_code = $this->get_pre_auth_code();

    	// $pre_auth_code = $pre_auth_code."KG5F";
    	$redirect_uri = urlencode("https://www.58zltc.com");
    	$url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid={$appid}&pre_auth_code={$pre_auth_code}&redirect_uri={$redirect_uri}";
        // $url = "";

    	$this->assign('url',$url);
        $this->display();
    }

    private function get_component_access_token(){
    	$token = S("component_access_token");
    	if($token){
    		return $token;
    	}
    	$url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";

    	$post_data = array(
    		"component_appid"=>C("OPEN_APPID"),
    		"component_appsecret"=>C("OPEN_APPSECRET"),
    		"component_verify_ticket"=>S("component_verify_ticket"));
    	$json = json_encode($post_data);
    	$res = $this->ihttp_post($url, $json);
    	$td = json_decode($res, true);
    	if($td['component_access_token']){
    		S("component_access_token", $td['component_access_token'], $td['expires_in'] - 120);
    		return $td['component_access_token'];
    	}else{
    		return false;
    	}
    }

    public function get_pre_auth_code(){
    	$code = S("pre_auth_code{$_SESSION['uid']}");
    	if($code){
    		return $code;
    	}
    	$token = $this->get_component_access_token();
    	if(!$token){
    		return "";
    	}

    	$url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token={$token}";
    	$post_data = array(
    		"component_appid"=>C("OPEN_APPID"));
    	$json = json_encode($post_data);
    	$res = $this->ihttp_post($url, $json);
    	$td = json_decode($res, true);
    	if($td['pre_auth_code']){
    		S("pre_auth_code", $td['pre_auth_code'], $td['expires_in'] - 60);
    		return $td['pre_auth_code'];
    	}else{
    		return "";
    	}
    }

    public function get_auth_info(){
    	// $auth_code = "queryauthcode@@@VwzhXmN0XJscE6-PGCeJbQ-jI35X5xxiiJEh3Pv3am17JWahatqLUMBT4ULFdp6sDmEKWYGbE4amSUdkCWTFsQ";
        $auth_code = $_GET['auth_code'];

    	$appid = C("OPEN_APPID");
    	$token = $this->get_component_access_token();
    	$url = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token={$token}";
    	$post_data = array(
    		"component_appid"=>$appid,
    		"authorization_code"=>$auth_code);
    	$json = json_encode($post_data);
    	$res = $this->ihttp_post($url, $json);
    	$td = json_decode($res, true);

    	$td = $td['authorization_info'];
        
        $isOk = false;
        foreach ($td['func_info'] as $key => $value) {
            if($value['funcscope_category']['id'] == 18){
                $isOk = true;
            }
        }
        if(!$isOk){
            $this->error("授权失败！请检查，小程序是否授权到其他第三方平台，小程序授权情况可在设置-第三方授权管理中查看，由于小程序部分权限集的唯一性，请先取消包括本平台在内的全部第三方平台授权后，重新回到本页面进行授权操作！");
        }

        $data['authorizer_access_token'] = $td['authorizer_access_token'];
        $data['authorizer_refresh_token'] = $td['authorizer_refresh_token'];
        $data['token_end_time'] = date("Y-m-d H:i:s", time()+7000);

    	$map['appid'] = $td['authorizer_appid'];
    	$url = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token={$token}";
    	$post_data = array(
    		"component_appid"=>$appid,
    		"authorizer_appid"=>$td['authorizer_appid']);
    	$json = json_encode($post_data);
    	$res = $this->ihttp_post($url, $json);
    	$td1 = json_decode($res, true);
    	$td1 = $td1['authorizer_info'];

        $data['nick_name'] = $td1['nick_name'];
        $data['head_img'] = $td1['head_img'];
        $data['user_name'] = $td1['user_name'];
        $data['principal_name'] = $td1['principal_name'];
        $data['signature'] = $td1['signature'];
        //$data['end_time'] = date("Y-m-d H:i:s",strtotime("+1 year",time()));
        if(S("mini_shopid")){
            $data['shop_id'] = S("mini_shopid");
            //$this->error('授权失败，请重试！shop_id缺失',U('index'));
        }
        if($_GET['type'] == 'reset'){
            $map['uid'] = session('uid');
            $map['appid'] = $td['authorizer_appid'];
            if(!M("Wechat")->where($map)->save($data)){
                S('mini_shopid',null);
                $this->error('授权失败，请重试！'.M("Wechat")->getLastSql(),U('index'));
            }else{
                //修改数据库数据
                if(S("mini_shopid")){
                    M("shop")->where(array("shop_id"=>$data['shop_id']))->setField(array("has_mini"=>2));
                }
                S('mini_shopid',null);
                $this->success('授权成功！',U('index'));
            }
        }else{
            $data['uid'] = session('uid');
            $data['appid'] = $td['authorizer_appid'];
            $data['create_time'] = date("Y-m-d H:i:s");
            if(M("Wechat")->where($map)->find()){
                M("Wechat")->where($map)->save($data);
                //修改数据库数据
                if(S("mini_shopid")){
                    M("shop")->where(array("shop_id"=>$data['shop_id']))->setField(array("has_mini"=>2));
                }
                S('mini_shopid',null);
                $this->error('授权成功！',U('index'));
                exit;
                //$this->error('该小程序已授权！请绑定别的小程序！',U('index'));
            }
            if($wid = M("Wechat")->add($data)){
                $cate_map['wid'] = 2;
                $cate_map['pid'] = 0;
                $sub_map['wid'] = 2;
                $cates = M("Cate")->where($cate_map)->select();
                foreach ($cates as $key => $value) {
                    $sub_map['pid'] = $value['id'];
                    unset($value['id']);
                    $value['wid'] = $wid;
                    $pid = M("Cate")->add($value);
                    $sub_cates = M("Cate")->where($sub_map)->select();
                    foreach ($sub_cates as $k => $v) {
                        unset($v['id']);
                        $v['wid'] = $wid;
                        $v['pid'] = $pid;
                        M("Cate")->add($v);
                    }
                }
                //修改数据库数据
                if(S("mini_shopid")){
                    M("shop")->where(array("shop_id"=>$data['shop_id']))->setField(array("has_mini"=>2));
                }
                S('mini_shopid',null);
                $this->success('授权成功！',U('index'));
            }else{
                S('mini_shopid',null);
                $this->error('授权失败，请重试！',U('index'));
            }
        }
    }
}